<?php
/**
 * User: xuanbang.wen
 * Date: 2019/12/30
 */

namespace App\Web\Controller;
use App\Command\ExportFile\ReportExportHelper;
use App\Web\Model\ProjectReport as ProjectReportModel;
use App\Web\Model\Project as ProjectModel;
use EchoPHP\Http\Request;


class ProjectReport extends Controller {
    /**
     * Notes:项目列表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function show(Request $request){
        $userId = $request->getParam('userid', 0);
        $teamCode = $request->getParam('teamcode', 0);
        $pageNum = $request->getParam('pagenum/d', 1);
        $pageLimit = $request->getParam('pagelimit/d', 10);
        $params = [
            'subname'=>$request->getParam('subname'),
            'projectname'=>$request->getParam('projectname'),
            'chargername'=>$request->getParam('chargername'),
            'ischarger'=>$request->getParam('ischarger'),
            'status'=>$request->getParam('status'),
        ];
        $projectModel = new ProjectModel();
        $projectReportModel = new ProjectReportModel();
        list($pageNum, $rowFrom, $rowTo) = $projectModel->paginationParameters($pageNum, $pageLimit);
        $count = $projectReportModel->projectListCount($params, $userId, $teamCode);
        $projectList = [];
        if ($count){
            $projectList = $projectReportModel->projectList($params, $userId, $teamCode, $rowFrom, $rowTo);
            $projectModel = new ProjectModel();
            $oprList = $projectModel->operatorList(array_column($projectList,'projectid'));
            foreach ($projectList as $key=>$project){
                $projectList[$key]['opr'] = $oprList[$project['projectid']] ?? [];
            }
        }
        return $this->json([
            'status'=>true,
            'message'=>'获取成功',
            'projectlist'=>$projectList,
            'totalcount' => intval($count),
            'pagenum' => $pageNum,
        ]);
    }

    /**
     * Notes:更新目标
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function updateWeeklyTarget(Request $request){
        $targetInfo = $request->getParam('targetinfo', []);
        $result = (new ProjectReportModel())->updateTarget($targetInfo);
        return $this->json($result);
    }

    /**
     * Notes:展示目标
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function showWeeklyTarget(Request $request){
        $projectId = $request->getParam('projectid', 0);
        $result = (new ProjectReportModel())->showTarget($projectId);
        return $this->json([
            'status'=>true,
            'message'=>'获取成功',
            'editright'=>$result['editright'],
            'targetlist'=>$result['targetlist'],
        ]);
    }

    /**
     * Notes:进度报表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function scheduleReport(Request $request){
        $projectId = $request->getParam('projectid', 0);
        $chargeWay = $request->getParam('chargeway', 0);
        $schueduleReport = (new ProjectReportModel())->scheduleReport($projectId, $chargeWay);
        return $this->json([
            'status'=>true,
            'message'=>'获取成功',
            'schuedulereport'=>$schueduleReport
        ]);
    }

    /**
     * Notes:推荐量周报表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function weeklyReport(Request $request){
        $projectId = $request->getParam('projectid', 0);
        $endDate = $request->getParam('enddate', '');
        $startDate = $request->getParam('startdate', '');
        $chargeWay = $request->getParam('chargeway', 0);

        if ($startDate && $endDate && ceil((strtotime($endDate)-strtotime($startDate))/86400) > 21){
            return $this->json([
                'status'=>false,
                'message'=>'时间跨度不能大于三周',
                'weeklyreport'=>[],
                'userlist'=>[]
            ]);
        }
        $result = (new ProjectReportModel())->weeklyReport($startDate, $endDate, $projectId, $chargeWay);
        return $this->json([
            'status'=>true,
            'message'=>'获取成功',
            'weeklyreport'=>$result['weeklyreport'],
            'userlist'=>$result['userlist']
        ]);
    }

    /**
     * Notes:推荐量月报表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function monthlyReport(Request $request){
        $projectId = $request->getParam('projectid', 0);
        $endDate = $request->getParam('enddate', '');
        $startDate = $request->getParam('startdate', '');
        $chargeWay = $request->getParam('chargeway', 0);
        $startMonth = date('m', strtotime($startDate));
        $startYear = date('Y', strtotime($startDate));
        $endMonth = date('m', strtotime($endDate));
        $endYear = date('Y', strtotime($endDate));
        $endMonth = $endYear > $startYear ? $endMonth + 12 : $endMonth;
        if ($startDate && $endDate && $endMonth - $startMonth > 2 ){
            return $this->json([
                'status'=>false,
                'message'=>'时间跨度不能大于三个月',
                'weeklyreport'=>[],
                'userlist'=>[]
            ]);
        }
        $result = (new ProjectReportModel())->monthlyReport($startDate, $endDate, $projectId, $chargeWay);
        return $this->json([
            'status'=>true,
            'message'=>'获取成功',
            'monthlylyreport'=>$result['monthlyreport'],
            'userlist'=>$result['userlist']
        ]);
    }

    /**
     * Notes:交易方式下的职位
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getCaseByChargeWay(Request $request){
        $projectId = $request->getParam('projectid', 0);
        $chargeWayId = $request->getParam('chargeway', '');
        $caseList = (new ProjectReportModel())->getCaseByChargeWay($chargeWayId,$projectId);
        return $this->json([
            'status'=>true,
            'message'=>'获取成功',
            'caselist'=>$caseList,
        ]);
    }

    /**
     * Notes:已交付人数详情
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function scheduleDetail(Request $request) {
        $pageNum = $request->getParam('pagenum/d', 1);
        $pageLimit = $request->getParam('pageLimit/d', 10);
        $searchParams = [
            'projectid' => $request->getParam('projectid', ''),
            'caseid'    => $request->getParam('caseid', ''),
            'flowat'    => $request->getParam('flowat', ''),
            'subid'     => $request->getParam('subid'),
            'oprid'     => $request->getParam('oprid'),
            'chargeway'     => $request->getParam('chargeway'),
            'keycodes'  => $request->getParam('keycodes'),
        ];

        $right = (new ProjectModel())->chkGetRight($searchParams['projectid']);
        if (!$right) {
            return $this->json([
                'status'     => false,
                'message'    => '无查看权限',
                'resumelist' => [],
            ]);
        }
        $caseResumeModel = new \App\Web\Model\CaseResume();
        $result = $caseResumeModel->getScheduleByElasticSearch($searchParams, $pageNum, $pageLimit);
        return $this->json($result);
    }

    /**
     * Notes:整体报表导出
     * @param Request $request
     * @return \EchoPHP\Http\Response\StreamedResponse
     * @throws \Exception
     */
    public function export(Request $request){
        $userId = $request->getParam('userid', 0);
        $teamCode = $request->getParam('teamcode', 0);
        $extraFields = $request->getParam('extrafields', '');
        $params = [
            'subname'=>$request->getParam('subname'),
            'projectname'=>$request->getParam('projectname'),
            'chargername'=>$request->getParam('chargername'),
            'ischarger'=>$request->getParam('ischarger'),
            'status'=>$request->getParam('status'),
        ];
        $projectReportModel = new ProjectReportModel();
        $count = $projectReportModel->projectListCount($params, $userId, $teamCode);
        $projectList = [];
        if ($count){
            $projectList = $projectReportModel->projectList($params, $userId, $teamCode, 0, 1000);
            $projectModel = new ProjectModel();
            $oprList = $projectModel->operatorList(array_column($projectList,'projectid'));
            foreach ($projectList as $key=>$project){
                $projectList[$key]['opr'] = $oprList[$project['projectid']] ?? [];
            }
        }
        return (new ReportExportHelper())->export($projectList, $extraFields);
    }

    /**
     * Notes:导出进度报表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse|\EchoPHP\Http\Response\StreamedResponse
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function exportSchedule(Request $request){
        $projectId = $request->getParam('projectid', 0);
        $chargeWay = $request->getParam('chargeway', 0);
        if (empty($projectId) || empty($chargeWay)){
            return $this->json([
                'status'=>false,
                'message'=>'导出失败',
            ]);
        }
        $scheduleReport = (new ProjectReportModel())->scheduleReport($projectId, $chargeWay);
        if(!$scheduleReport){
            return $this->json([
                'status'=>false,
                'message'=>'导出失败',
            ]);
        }
        return (new ReportExportHelper())->exportSchedule($scheduleReport, $projectId);
    }

    /**
     * Notes:导出推荐量周/月报
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse|\EchoPHP\Http\Response\StreamedResponse
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function exportRecommend(Request $request){
        $projectId = $request->getParam('projectid', 0);
        $endDate = $request->getParam('enddate', '');
        $startDate = $request->getParam('startdate', '');
        $chargeWay = $request->getParam('chargeway', 0);
        $reportType = $request->getParam('reporttype', 0);
        $oprIds = $request->getParam('oprids', '');
        $oprIds = array_filter(explode(',', $oprIds));
        if (empty($oprIds)){
            return $this->json([
                'status'=>false,
                'message'=>'未选择顾问',
            ]);
        }
        $projectReportModel = new ProjectReportModel();
        $exportHelper = new ReportExportHelper();
        if ($reportType == 'weeklyreport'){
            if ($startDate && $endDate && ceil((strtotime($endDate)-strtotime($startDate))/86400) > 21){
                return $this->json([
                    'status'=>false,
                    'message'=>'时间跨度不能大于三周',
                ]);
            }
            $recommendReport = $projectReportModel->weeklyReport($startDate, $endDate, $projectId, $chargeWay);
            return $exportHelper->exportWeekLyRecommend($recommendReport, $oprIds);
        }elseif ($reportType == 'monthlyreport'){
            $startMonth = date('m', strtotime($startDate));
            $startYear = date('Y', strtotime($startDate));
            $endMonth = date('m', strtotime($endDate));
            $endYear = date('Y', strtotime($endDate));
            $endMonth = $endYear > $startYear ? $endMonth + 12 : $endMonth;
            if ($startDate && $endDate && $endMonth - $startMonth > 2 ){
                return $this->json([
                    'status'=>false,
                    'message'=>'时间跨度不能大于三个月',
                ]);
            }
            $recommendReport = $projectReportModel->monthlyReport($startDate, $endDate, $projectId, $chargeWay);
            return $exportHelper->exportMonthlyRecommend($recommendReport, $oprIds);
        }else{
            return $this->json([
                'status'=>false,
                'message'=>'导出失败',
            ]);
        }
    }
}